package cn.dyhack.bibiscan.controller.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.dyhack.bibiscan.aop.UserTokenValidAnnotation;
import cn.dyhack.bibiscan.controller.UserController;
import cn.dyhack.bibiscan.po.tables.pojos.User;
import cn.dyhack.bibiscan.service.UserService;
import cn.dyhack.bibiscan.util.JwtUtils;
import cn.dyhack.bibiscan.util.code.CommonRespType;
import cn.dyhack.bibiscan.vo.CommonResp;
import cn.dyhack.bibiscan.vo.VoLoginUser;
import cn.dyhack.bibiscan.vo.VoUser;

/**
 * 
 * 用户控制层实现类
 *
 * @author zhangke
 * @since 0.0.1
 */
@RestController
public class UserControllerImpl implements UserController {
   
    
    private static final Logger LOG = LoggerFactory.getLogger(UserControllerImpl.class);

    
    @Autowired
    UserService userService;
    
    @UserTokenValidAnnotation
    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public CommonResp addUser( HttpServletRequest request,User user) {
        CommonResp commonResp = new CommonResp();
        if(userService.addUser(user))
        {
            commonResp.setCode(CommonRespType.SUCCESS_RESPONSE.getCode());
            commonResp.setMessage(CommonRespType.SUCCESS_RESPONSE.getMessage());
        }
        commonResp.setCode(CommonRespType.FAIL_RESPONSE.getCode());
        commonResp.setMessage(CommonRespType.FAIL_RESPONSE.getMessage());
        return commonResp;
    }

    @RequestMapping(value = "/users/{user-id}", method = RequestMethod.GET)
    @Override
    @UserTokenValidAnnotation
    public VoUser selectUser( HttpServletRequest request, @PathVariable(value = "user-id") Long userId) {
        return userService.selectUser(userId);
    }
    @UserTokenValidAnnotation
    @RequestMapping(value = "/users/{user-id}",method = RequestMethod.DELETE)
    @Override
    public void delUser(Long userId, String token) {
        userService.delUser(userId);

    }
     
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @Override
    public CommonResp login(HttpServletResponse response,@RequestBody VoLoginUser voLoginUser) {
        Map<String,String> map = new HashMap<>();
        CommonResp commonResp = new CommonResp();
        Map<String,String> tokenMap = new HashMap<>();
        List<Map<String,String>> data = new ArrayList<>();
        if(userService.selectUser(voLoginUser.getUsername()).getPasswordSalt().equals(voLoginUser.getPassword()))
        {
            map.put("username", voLoginUser.getUsername());
            map.put("userid", userService.selectUser(voLoginUser.getUsername()).getId().toString());
            
            String token = null;;
            try {
                token = JwtUtils.createToken(map);
                tokenMap.put("token", token);
                data.add(tokenMap);
            } catch (Exception e) {
                LOG.error("生成token失败");
                e.printStackTrace();
                
               
            }
            Cookie cookie = new Cookie("token", token);
            LOG.debug("设置有效时间为2小时");
            cookie.setMaxAge(7200);
            cookie.setPath("/");
            LOG.debug("把jsonwebtoken存入到cookie里面");
            response.addCookie(cookie);
            commonResp.setCode(CommonRespType.LOGIN_SUCCESS.getCode());
            commonResp.setMessage(CommonRespType.LOGIN_SUCCESS.getMessage());
            commonResp.setData(data);
            return commonResp;
            
        }
        
        commonResp.setCode(CommonRespType.FAIL_RESPONSE.getCode());
        commonResp.setMessage(CommonRespType.FAIL_RESPONSE.getMessage());
        return commonResp;
    }
    @UserTokenValidAnnotation
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    @Override
    public CommonResp logout( HttpServletRequest request,HttpServletResponse response,String userName) {
        CommonResp commonResp = new CommonResp();
        Cookie[] cookies=request.getCookies();
        if(cookies!=null)
        {
            for(Cookie cookie: cookies)
            {
                if(cookie.getName().equals("token"))
                {
                    Cookie returnCookie = new Cookie("token", null);
                    //设置cookie过期
                    returnCookie.setMaxAge(0);
                    response.addCookie(returnCookie);
                }
            }
        }
        
        return commonResp;
        
    }


}
